package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.Goods;
import com.scau.yangsuiyu.estore.dababases.entity.OrderDetail;
import com.scau.yangsuiyu.estore.dababases.entity.Seller;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.ArrayList;
import java.util.List;

/**
 * @author suiyu_yang
 * @description
 * @date 2019-06-20 23:40
 * @email suiyu_yang@163.com
 */
public class OrderDetailDao {
    public void insert(OrderDetail orderDetail) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(orderDetail);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void delete(OrderDetail orderDetail) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(orderDetail);

        transaction.commit();
        HibernateUtil.closeSession();

    }

    public void update(OrderDetail orderDetail) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(orderDetail);

        //当事务提交时，hibernate会自动按照一定的策略将session中的持久化对象，同步到数据库中，从而自动使数据库的状态和session中的对象状态完全一致。
        // 如果要在事务提交前同步，则可以使用session的flush方法。
        session.flush();

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public List<OrderDetail> getOrderDetailByOrderId(int orderId) {
        Session session = HibernateUtil.currentSession();

        String sql = "from OrderDetail orderDetail where orderDetail.orderId = '" + orderId + "' ";

        List<OrderDetail> orderDetails = session.createQuery(sql).list();

        HibernateUtil.closeSession();
        return orderDetails;
    }

    public List<OrderDetail> getOrderDetailBySeller(Seller seller) {
        Session session = HibernateUtil.currentSession();

        String sql = "from OrderDetail orderDetail ";

        List<OrderDetail> orderDetails = session.createQuery(sql).list();
        HibernateUtil.closeSession();

        List<Goods> goodsList = seller.getShop().getGoodsList();
        List<OrderDetail> resultList = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetails) {
            int itemId = orderDetail.getItemId();
            for (Goods goods : goodsList) {
                Goods tempGoods = new ItemDao().getItemByItemId(itemId).getGoods();
                if (tempGoods.getId() == goods.getId()) {
                    resultList.add(orderDetail);
                }
            }
        }

        return resultList;
    }

}
